package com.FindMyStuff.Activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.FindMyStuff.Model.DataAccessor;
import com.FindMyStuff.Model.DataBaseHelper;
import com.FindMyStuff.Model.Item;
import com.FindMyStuff.Model.ItemCategory;
import com.FindMyStuff.Model.ItemType;
import com.FindMyStuff.Model.SessionManager;

public class UserItemsActivity extends ListActivity {
	/**
	 * Holds the SessionManager so garbage collection will not get rid of the session manager
	 */
	private SessionManager sm;
	private ArrayAdapter<Item> adapter;
	private ArrayList<Item> values;
	private ArrayList<Item> displayValues;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_items);
		
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setIcon(getResources().getIdentifier("ic_home", "drawable",  getPackageName()));
		
		
		sm = SessionManager.getInstance();
		DataBaseHelper dbh = new DataBaseHelper(this);
		DataAccessor da = new DataAccessor(dbh);
		ItemType lostOrFound = ItemType.convertToType(getIntent().getStringExtra("Text"));
		boolean itemOrNoItem = getIntent().getStringExtra("item") != null;
		//Spinner for select
		Spinner spinner = (Spinner) findViewById(R.id.item_category);
		Spinner lostFoundSpinner = (Spinner) findViewById(R.id.lostorfound);
		
		//lost or found spinner setup
		ArrayAdapter<CharSequence> lostFoundSpin = ArrayAdapter.createFromResource(this,
		        R.array.lost_or_found_select, android.R.layout.simple_spinner_item);
		
		lostFoundSpin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		lostFoundSpinner.setAdapter(lostFoundSpin);
		
		
		//category spinner setup
		ArrayAdapter<CharSequence> categorySpin = ArrayAdapter.createFromResource(this,
		        R.array.item_category_select, android.R.layout.simple_spinner_item);
		
		categorySpin.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(categorySpin);
		
		if(lostOrFound.equals(ItemType.All))
		{
			values = da.getItemsByUser(sm.getCurrentUser());
			displayValues = values;
			lostFoundSpinner.setSelection(0);
		} else 
		{ 
			values = da.getItemsByUser(sm.getCurrentUser());
			displayValues = da.getItemsByUser(sm.getCurrentUser(), lostOrFound);
			if(lostOrFound.equals(ItemType.Lost))
			{
				lostFoundSpinner.setSelection(1);
			} else 
			{
				lostFoundSpinner.setSelection(2);
			}
		}

		adapter = new ArrayAdapter<Item>(this,
				android.R.layout.simple_list_item_1, displayValues);
		setListAdapter(adapter);
		
		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {filter();}
			public void onNothingSelected(AdapterView<?> parent) {}   });
		
		lostFoundSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {filter();}
			public void onNothingSelected(AdapterView<?> parent) {} });
		
		//Set up date text
		EditText dateText = (EditText)findViewById(R.id.time);
		dateText.addTextChangedListener(new TextWatcher(){
	        public void afterTextChanged(Editable s) {
	            filter();
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
	        public void onTextChanged(CharSequence s, int start, int before, int count){}
	    });
		
		RadioGroup rGroup = (RadioGroup) findViewById(R.id.radioDateSelection);
		rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				filter();
			}
		});
		if(itemOrNoItem)
		{
			Dialog dialogMatched = createMatchItemDialog(sm.matchedItem);
			dialogMatched.show();
		}
	}
		
	/**
	 * Creates a dialog to tell the user the inputed data is incorrect
	 * @param error message to display to user
	 * @return dialog to show user
	 */
	public Dialog createMatchItemDialog(Item item) {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);

	    // Inflate and set the layout for the dialog
	    // Pass null as the parent view because its going in the dialog layout
	    builder.setMessage("Do this item match the item you entered?\n" + item);
	    builder.setPositiveButton(R.string.Yes, new DialogInterface.OnClickListener() {
	               @Override
	               public void onClick(DialogInterface dialog, int id) {
	        
	               }
	           });
	    builder.setNegativeButton(R.string.No, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                
            }
        });
	    return builder.create();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_user_items, menu);
				
		return true;
	}
	
	
	
	/**
	 * Filters the items on the page based on the user input
	 */
	@SuppressLint("SimpleDateFormat")
	public void filter() {
		
		//Get date from text
		EditText dateText = (EditText)findViewById(R.id.time);
		String dateString = dateText.getText().toString();
		String delims = "[/]";
		String[] dateVals = dateString.split(delims);
		Date date;
		if(dateVals.length == 3) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			try {
				date = sdf.parse(dateString);
			} catch (ParseException e) {
				System.out.println("UNABLE TO PARSE STRING INTO DATE FOR ITEM!!!!");
				date = null;
			}
		} else {
			date = null;
		}


		Spinner lost_or_found = (Spinner) findViewById(R.id.lostorfound);
		Spinner category_spinner = (Spinner) findViewById(R.id.item_category);
		ItemCategory category = ItemCategory.convertStringtoCategory(category_spinner.getSelectedItem().toString());
		ItemType type = ItemType.convertStringToType(lost_or_found.getSelectedItem().toString());
		ItemCategory all = ItemCategory.convertStringtoCategory("All");
		ItemType allType = ItemType.convertStringToType("All");
		
		displayValues = new ArrayList<Item>();
		//Filter category
		Boolean ifLostFound; 
		Boolean ifCategory;
		Boolean ifDate = false;
		
		for(Item i:values) {
			ifLostFound = ((i.getItemType().equals(type)) || type.equals(allType)) ; 
			ifCategory = ((i.getItemCategory().equals(category)) || category.equals(all)) ;
			if(date != null)
			{
				RadioButton rAfter = (RadioButton) findViewById(R.id.radioAfter);
				RadioButton rBefore = (RadioButton) findViewById(R.id.radioBefore);
				if(rAfter.isChecked())
				{
					ifDate = i.getDate().after(date);
				} else if(rBefore.isChecked())
				{
					ifDate = i.getDate().before(date);
				} else
				{
					ifDate = i.getDate().equals(date);
				}
			}
		
			if( ifLostFound && ifCategory ) {
				if(date != null)
				{
					if(ifDate)
					{
						displayValues.add(i);
					}
				} else
				{
					displayValues.add(i);
				}
			}
		}

		adapter = new ArrayAdapter<Item>(this,
				android.R.layout.simple_list_item_1, displayValues);
		setListAdapter(adapter);
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent toHome = new Intent(this, HomeActivity.class);
			startActivity(toHome);
			overridePendingTransition  (R.anim.left_slide_out, R.anim.left_slide_in);
			return true;
		case R.id.menu_logout:
			Intent intent = new Intent(this, LogInActivity.class);
			sm.logout();
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
